package com.xuwei.base.reflect;

import java.lang.reflect.Constructor;

import org.junit.Test;

public class Demo1 {
	//反射：public Person()
	@Test
	public void test1() throws Exception{
		//得到字节码
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");//代表Person类在内存中的字节码对象
//		Class clazz = p.getClass();
//		Class clazz = Person.class;
		Constructor c = clazz.getConstructor(null);//得到构造方法干嘛？创建对象
		c.newInstance(null);
		
	}
	@Test
	public void test11() throws Exception{
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");
		Person p = (Person)clazz.newInstance();//调用默认的构造方法
		System.out.println(p.name);
	}
	//反射：public Person(String name)
	@Test
	public void test2() throws Exception{
		//得到字节码
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");//代表Person类在内存中的字节码对象
		Constructor c = clazz.getConstructor(String.class);
		c.newInstance("bob");
		
	}
	@Test//public Person(String name,int age)
	public void test3() throws Exception{
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");
		Constructor c = clazz.getConstructor(String.class,int.class);
		Person p = (Person)c.newInstance("bob",20);
		System.out.println(p.name);
		
	}
	@Test//private Person(int age)
	public void test4() throws Exception{
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");
		Constructor c = clazz.getDeclaredConstructor(int.class);//读取私有的构造方法的
		c.setAccessible(true);//暴力反射
		Person p = (Person)c.newInstance(20);
		System.out.println(p.name);
		
	}
	@Test//类中的所有构造方法
	public void test5() throws Exception{
		Class clazz = Class.forName("com.xuwei.base.reflect.Person");
		Constructor[]  cs = clazz.getDeclaredConstructors();
		System.out.println(cs.length);
		
	}
}
